﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.ComponentModel;

namespace Phone.Framework.Behaviors
{
    public class PageBehavior
    {

        public static bool GetExitPrompt(DependencyObject obj)
        {
            return (bool)obj.GetValue(ExitPromptProperty);
        }

        public static void SetExitPrompt(DependencyObject obj, bool value)
        {
            obj.SetValue(ExitPromptProperty, value);
        }

        public static readonly DependencyProperty ExitPromptProperty =
            DependencyProperty.RegisterAttached("ExitPrompt", typeof(bool), typeof(PageBehavior),
            new PropertyMetadata(false, (sender, arg) =>
            {
               
                    var element = sender as PhoneApplicationPage;
                    ExitPromptBehavior.ExitPrompt(element, (bool)arg.NewValue);
            }));


        internal class ExitPromptBehavior
        {
            public static void ExitPrompt(PhoneApplicationPage page, bool showWarn)
            {
                if (showWarn)
                    page.BackKeyPress += new EventHandler<CancelEventArgs>(page_BackKeyPress);
                else
                    page.BackKeyPress -= new EventHandler<CancelEventArgs>(page_BackKeyPress);
            }

            static void page_BackKeyPress(object sender, CancelEventArgs e)
            {
                var result = MessageBox.Show("Are you sure you want to quit?", "", MessageBoxButton.OKCancel);
                switch (result)
                {
                    case MessageBoxResult.Cancel:
                        e.Cancel = true;
                        break;
                }
            }
        }
    }
}